﻿using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DailyApp.WPF.HttpClients
{
    /// <summary>
    /// api请求工具类
    /// </summary>
    public class HttpRestClient
    {
        private readonly RestClient Client;
        private readonly string baseUrl = "https://localhost:7071/api/";

      public HttpRestClient()
        {
            Client = new RestClient();
        }
        public async Task<ApiResponse<output>> Execute<input,output>(ApiRequest<input> apiRequest) {
            try
            {
                RestRequest request = new RestRequest(apiRequest.Method);
                request.AddHeader("Content-Type", apiRequest.ContentType);
                if (apiRequest.Parameters != null)
                {
                    //request.Parameters.Add(new Parameter("param", apiRequest.Parameters, ParameterType.RequestBody));
                    request.AddParameter("param", JsonConvert.SerializeObject(apiRequest.Parameters), ParameterType.RequestBody);
                }
                Client.BaseUrl = new Uri(baseUrl + apiRequest.Route);
                var result = await Client.ExecuteAsync(request);
                var resultObject = JsonConvert.DeserializeObject<ApiResponse<output>>(result.Content);
                resultObject.IsSuccess = result.IsSuccessful;
                return resultObject;
                //return new ApiResponse<output>()
                //{
                //    ResultCode = (int)result.StatusCode,
                //    Msg = $"请求失败: {result.Content}",
                //    Errors = new List<ErrorDetail> { new ErrorDetail { Message = result.ErrorMessage ?? result.Content } }
                //};
            }
            catch (Exception ex)
            {
                return new ApiResponse<output>
                {
                    ResultCode = -99,
                    Msg = "请求异常",
                    Errors = new List<ErrorDetail> { new ErrorDetail { Message = ex.Message } }
                };
            }
        }
    }
}
